<template>
  <view class="classify-container">
    <view class="p-classify">
      <view v-for="(item, i) in datas.list" :key="i">
        <view
          :class="'n-l-items ' + (datas.currentIndex == i ? 'active' : '')"
          @tap="switchRightTab(i)"
          >{{ item.name || '' }}
        </view>
      </view>
    </view>

    <view class="p-list p-b-180rpx">
      <!-- 一级分类banner -->
      <view class="banner" v-if="datas.list[datas.currentIndex]?.image">
        <view
          class="img-box"
          @tap="linkMiniPragram(datas.list[datas.currentIndex].linkAppid, list[currentIndex].link)"
        >
          <image :src="bannerShow" mode="scaleToFill" />
        </view>
      </view>

      <!-- 只有一级类目 -->
      <view v-if="datas.layer === 1">
        <view class="item-wrap" v-for="(x, index) in datas.allSpus" :key="index">
          <template v-if="x.category_id === datas.list[datas.currentIndex].id">
            <view class="n-r-item" @tap="toProductView(x.id)">
              <view class="imgbox">
                <img class="thumbnail" :src="handleUnitImg(x)" mode="aspectFit" />
              </view>
              <view class="intro">
                <view class="caption lineText2">
                  <label class="label" v-if="x.activityTitle">{{ x.activityTitle }}</label>
                  <label class="label" v-if="x.activitySubTitle">{{ x.activitySubTitle }}</label>
                  <text>{{ x.title || '' }}</text>
                </view>
                <view class="ext-label" v-if="x.haveCoupon && x.couponTitles.length > 0">
                  <view class="ext-label-item">
                    <text class="before"></text>
                    <text>{{ x.couponTitles[0] }}</text>
                    <text class="after"></text>
                  </view>
                </view>
                <view class="price" v-if="x.price">
                  <span class="price"> ￥{{ x.promotionPrice || x.vipPrice }} </span>
                  <span class="ori-price">￥{{ x.price }}</span>
                </view>
              </view>
            </view>
          </template>
        </view>
      </view>

      <!-- 有二级类目 -->
      <view v-else-if="datas.layer === 2" class="menu-list">
        <view v-for="(n, index2) in datas.list[datas.currentIndex].children" :key="index2">
          <view class="wrap">
            <view class="main-title">{{ n.name || '' }}</view>
            <view class="icon" @tap="toProductList(n.id)">全部 》</view>
          </view>
          <view
            class="adv"
            v-if="n.image"
            @tap="
              linkMiniPragram(
                datas.list[datas.currentIndex].linkAppid,
                datas.list[datas.currentIndex].link,
              )
            "
          >
            <image :src="n.image || ''" mode="aspectFit" />
          </view>
          <template v-if="datas.allSpus.some((e) => n.id == e.category_id)">
            <view
              class="item-wrap"
              v-for="(y, index3) in datas.allSpus.filter((e) => e.category_id == n.id)"
              :key="index3"
            >
              <template>
                <view class="n-r-item" @tap="toProductView(y.id)">
                  <view class="imgbox">
                    <img class="thumbnail" :src="handleUnitImg(y)" mode="aspectFit" />
                  </view>
                  <view class="intro">
                    <view class="caption lineText2">
                      <label class="label" v-if="y.activityTitle">{{ y.activityTitle }}</label>
                      <label class="label" v-if="y.activitySubTitle">{{
                        y.activitySubTitle
                      }}</label>
                      <text>{{ y.title || '' }}</text>
                    </view>
                    <view class="ext-label" v-if="y.haveCoupon && y.couponTitles.length > 0">
                      <view class="ext-label-item">
                        <text class="before"></text>
                        <text>{{ y.couponTitles[0] }}</text>
                        <text class="after"></text>
                      </view>
                    </view>
                    <view class="price" v-if="y.price">
                      <span class="price"> ￥{{ y.promotionPrice || y.vipPrice || '' }} </span>
                      <span class="ori-price">￥{{ y.price || '' }}</span>
                    </view>
                  </view>
                </view>
              </template>
            </view>
          </template>
        </view>
      </view>

      <!-- 有三级分类 -->
      <view v-else-if="datas.layer === 3" class="menu-list">
        <!-- 二级目录 -->
        <view
          class="menu-item"
          v-for="(n, index4) in datas.list[datas.currentIndex].children"
          :key="index4"
        >
          <view class="wrap">
            <view class="main-title">{{ n.name || '' }}</view>
            <view class="icon" @tap="toProductList(n.id)">全部 》</view>
          </view>

          <view class="item-list">
            <!-- 存在三级目录 -->
            <view class="third-layer" v-if="n.children?.length >= 1">
              <view
                class="item"
                v-for="(m, index5) in n.children"
                :key="index5"
                @tap="toProductList(m.id)"
              >
                <view class="img-box">
                  <image :src="handleUnitImg(m) || ''" mode="aspectFit" />
                </view>
                <view class="sub-title">{{ m.name || '' }}</view>
              </view>
            </view>
            <!-- 不存在三级目录,只显示二级目录产品 -->
            <view v-else>
              <view
                class="item-wrap"
                v-for="(z, index6) in datas.allSpus"
                :key="index6"
                v-if="z.category_id === n.id"
              >
                <view class="n-r-item" @tap="toProductView(z.id)">
                  <view class="imgbox">
                    <img class="thumbnail" :src="z.image" mode="aspectFit" />
                  </view>
                  <view class="intro">
                    <view class="caption lineText2">
                      <label class="label" v-if="z.activityTitle">{{ z.activityTitle }}</label>
                      <label class="label" v-if="z.activitySubTitle">{{
                        z.activitySubTitle
                      }}</label>
                      <text>{{ z.title || '' }}</text>
                    </view>
                    <view class="ext-label" v-if="z.haveCoupon && z.couponTitles.length > 0">
                      <view class="ext-label-item">
                        <text class="before"></text>
                        <text>{{ z.couponTiles[0] }}</text>
                        <text class="after"></text>
                      </view>
                    </view>
                    <view class="price" v-if="z.price">
                      <span class="price"> ￥{{ z.promotionPrice || z.vipPrice }} </span>
                      <span class="ori-price">￥{{ z.price || '' }}</span>
                    </view>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>

      <view v-else></view>
    </view>
  </view>
</template>

<script lang="ts" setup>
  import { PATH_COLLECTIONS } from '@/enums/routerEnum';
  import { getProductClassify, productsByCateIdLimit } from '@/services/api/products/products';
  import { router } from '@/utils/router';
  import { onShow } from '@dcloudio/uni-app';
  import { computed, onMounted, reactive, watch } from 'vue';

  const datas = reactive({
    currentIndex: null as any,
    list: [] as Array<ClassifyModel>,
    dataList: [] as Array<any>,
    currentSpus: [] as Array<ProductsModel>,
    allSpus: [] as Array<ProductsModel>,
    layer: 1,
  });

  const bannerShow = computed(() => {
    if (datas.currentIndex !== null) {
      return datas.list[datas.currentIndex]?.image;
    }
    return '';
  });

  watch(
    () => datas.currentIndex,
    async (n: any) => {
      if (datas.list[n] && datas.list[n].hasOwnProperty('id')) {
        const l = getLayer(datas.list[n], 'children', 'parent_group_code');
        datas.layer = l;
        await getSpuList(datas.list[n]?.id);
      }
    },
    { immediate: true },
  );

  onMounted(async () => {
    await loadClassify();
    // 加载分类后再初始数据
    initDatas();
  });

  // onShow(async () => {
  //   await loadClassify();
  //   // 加载分类后再初始数据
  //   initDatas();
  // });

  const initDatas = () => {
    datas.currentIndex = 0;
    datas.layer = 1;
  };

  const handleUnitImg = (row: any) => {
    if (!row.img_url) return '';
    return row.img_url.split(',')[0];
  };

  // 只显示前两个优惠券
  const spliceCoupon = (data) => {
    console.log('data: ', data);
    return [...data].splice(0, 2);
  };
  const loadClassify = () => {
    return new Promise<any>(async (resolve, reject) => {
      const result = await getProductClassify();
      const classifies = result.data;
      if (classifies && classifies.length > 0) {
        datas.list = classifies;
        resolve(classifies);
      }
    });
  };
  // 根据分类查所有spu
  const getSpuList = async (cateId: number) => {
    return new Promise<void>((resolve, reject) => {
      const opt = {
        id: cateId,
      };
      productsByCateIdLimit(opt)
        .then((res) => {
          console.log('res: ', res);
          datas.allSpus = res.data;
          resolve(true);
        })
        .catch((e) => {
          console.log(e);
        });
    });
  };

  // banner跳转小程序
  const linkMiniPragram = (appId = '', path = '') => {
    uni.navigateToMiniProgram({
      appId,
      path,
      success: (result) => {
        console.log(result);
      },
      fail: (error) => {
        console.log(error);
      },
    });
  };

  //根据所有产品筛选当前分类产品
  const filterSpusById = (cateId: number) => {
    console.log('二级Id', cateId);
    return datas.allSpus.filter((e: any) => {
      return e?.category_id === cateId;
    });
  };

  const switchRightTab = (index: number) => {
    datas.currentIndex = index || 0;
    // this.loadClassify()
  };

  const toProductView = (e) => {
    console.log(e);
    router.push(PATH_COLLECTIONS.PRODUCTVIEW + `?id=${e}`);
  };

  // 跳转商品列表
  const toProductList = (id) => {
    uni.navigateTo({ url: '/pages/footer/news/productList?categoryId=' + id });
  };

  // 遍历多层列表数据
  const deepdata = (arr: any, products = []): any => {
    if (arr && arr.length > 0) {
      for (let i = 0; i < arr.length; i++) {
        if (
          Object.prototype.hasOwnProperty.call(arr[i], 'children') &&
          Array.isArray(arr[i].children) &&
          arr[i].children.length > 0
        ) {
          products = products.concat(arr[i].productSpuRespVOList);
          return deepdata(arr[i].children, products);
        } else {
          products = products.concat(arr[i].productSpuRespVOList);
        }
      }
      console.log(products);
      return products;
    }
  };

  /**
   *
   * @param {Object} obj 分类数据
   * @param {String} attr 子集的属性
   * @param {String} depthFiled 当前层级的父级节点id列表 1,2
   * @return {Number} 返回数组层级
   */
  const getLayer = (obj: ClassifyModel, attr: string, depthFiled: string): any => {
    let stack = obj[attr] ? [obj] : [];
    let res = [],
      group_codes = [];
    while (stack.length) {
      let node = stack.pop() || [];
      if (node[attr] && node[attr].length) {
        res.push(...node[attr]);
      }

      if (node[attr] && node[attr].length) {
        stack.push(...node[attr]);
      }
    }

    group_codes = res.map((e) => {
      return e[depthFiled] ? e[depthFiled].split(',').length + 1 : 1;
    });

    return group_codes.length > 0 ? Math.max(...group_codes) : 1;
  };
</script>

<style scoped lang="scss">
  .classify-container {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    box-sizing: border-box;
    position: relative;
    width: 100%;
    height: calc(100vh - 100rpx);
    background-color: #fff;
  }

  // 商品分类
  .p-classify {
    display: inline-block;
    width: 25%;
    height: 100%;
    background: #f2f2f2;
    text-align: center;
    overflow: scroll;
  }

  .p-classify .n-l-items {
    height: 100rpx;
    line-height: 100rpx;
    text-align: center;
    font-size: 28rpx;
    position: relative;
    overflow: scroll;
    white-space: nowrap;
    text-overflow: ellipsis;
  }

  .p-classify .n-l-items.active {
    color: #cc0a2d;
    background-color: #fff;
    border-left: 4rpx solid #cc0a2d;
  }

  //商品列表
  .p-list {
    flex: 1;
    width: 75%;
    height: 100%;
    background: #fff;
    overflow-y: scroll;

    .banner {
      padding: 10rpx;

      .img-box {
        width: 100%;
        height: 160rpx;

        image {
          width: 100%;
          height: 100%;
        }
      }
    }

    // 二级类目
    .menu-list {
      padding: 24rpx;

      .menu-item {
        margin-bottom: 30rpx;
      }

      .wrap {
        height: 80rpx;
        line-height: 80rpx;
        display: flex;
        justify-content: space-between;

        .main-title {
          font-weight: bold;
        }
      }

      .adv {
        width: 100%;
        height: 724rpx;

        image {
          width: 100%;
          height: 100%;
        }
      }

      .item-list {
        .third-layer {
          display: flex;
          flex-flow: row wrap;
          width: 100%;
        }

        .item {
          width: 33%;

          .img-box {
            background: #f8f8f8;
            border: 1px solid #f8f8f8;
            width: 100%;
            height: 160rpx;

            image {
              width: 100%;
              height: 100%;
            }
          }

          .sub-title {
            text-align: center;
          }
        }
      }
    }
  }

  .p-list .item-wrap {
    padding: 10rpx;
    background-color: #fff;
  }

  .p-list .item-wrap .n-r-item {
    padding: 16rpx 0;
    height: 100%;
    box-sizing: border-box;
    overflow: hidden;
    border-bottom: 1px solid #ddd;
  }

  .p-list .item-wrap .n-r-item .imgbox {
    float: left;
    width: 33.3%;
    text-align: center;
    margin-right: 30rpx;
    box-sizing: border-box;
  }

  .p-list .item-wrap .n-r-item .imgbox .thumbnail {
    width: 100%;
    height: 176rpx;
  }

  .p-list .item-wrap .intro {
    flex: 1;
    text-align: left;
    display: flex;
    justify-content: space-between;
    flex-direction: column;
    overflow: scroll;
    min-height: 178rpx;
    max-height: 200rpx;
  }

  .p-list .item-wrap .intro .caption {
    color: #333;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
    box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: normal;
    line-height: 180%;

    .label {
      background: linear-gradient(45deg, #ff862b, #ff5858);
      font-size: 22rpx;
      display: inline-block;
      color: #fff;
      margin-right: 20rpx;
      padding: 0 10rpx;
      border-radius: 8rpx;
    }

    .label:nth-of-type(1) {
      background: linear-gradient(45deg, #ff0000, #ff5858bf);
    }
  }

  .p-list .item-wrap .intro .ext-label {
    display: flex;
    flex-flow: row wrap;

    .ext-label-item {
      height: 40rpx;
      line-height: 40rpx;
      margin-left: 20rpx;
      padding: 0 12rpx;
      font-size: 24rpx;
      margin-bottom: 8rpx;
      border: 2rpx solid #ff5858;
      border-radius: 8rpx;
      color: #ff5858;
      position: relative;
    }

    .before {
      left: -10rpx;
      background: #fff;
      top: 8rpx;
      position: absolute;
      width: 16rpx;
      height: 16rpx;
      border-right: 2rpx solid #ff5858;
      border-radius: 50%;
    }

    .after {
      right: -12rpx;
      background: #fff;
      top: 8rpx;
      position: absolute;
      width: 16rpx;
      height: 16rpx;
      border-left: 2rpx solid #ff5858;
      border-radius: 50%;
    }
  }

  .p-list .item-wrap .intro .price {
    color: #cc0a2d;
    font-size: 36rpx;
  }

  .p-list .item-wrap .intro .ori-price {
    margin-left: 20rpx;
    color: #ccc;
    text-decoration: line-through;
    font-weight: 400;
    font-size: 24rpx !important;
  }
</style>
